package com.seven.commons;

import clover.com.google.gson.Gson;
import clover.com.google.gson.GsonBuilder;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.log4j.Logger;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;


/**
 * @类名: JsonUtils
 * @描述: json转换工具 只是针对VO起作用
 * @作者: zfh
 * @author :zfh
 * @时间: 2016年3月23日 下午5:23:09
 */
public class JsonUtils {

	private static final Logger LOGGER = Logger.getLogger(JsonUtils.class);

	private static final String COLLECTION_STR_LIST = "List";
    private static final String COLLECTION_STR_MAP = "Map";

    /**
     * 定义jackson对象
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();
    static {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        MAPPER.setDateFormat(format);
    }


    private static final Gson gson = new GsonBuilder()
            //设置日期的格式
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            //防止对网址乱码 忽略对特殊字符的转换
            .disableHtmlEscaping()
            .create();

    /**
     * @方法名: objectToJson
     * @描述: 将对象转换成json字符串
     * @param data
     * @return String
     */
    public static String objectToJson(Object data) {
    	try {
    	    //判断是否是集合类型
            if (Objects.isNull(data)){
                return null;
            }
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 将json结果集转化为对象
     * @param jsonData json数据
     * @param beanType 对象中的object类型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
            LOGGER.error("json to obj error",e);
        }
        return null;
    }
    
    /**
     * @方法名: jsonToList
     * @描述: 将json数据转换成pojo对象list
     * @param jsonData
     * @param beanType
     * @return List<T>
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
            LOGGER.error("json to list error",e);
		}
    	return null;
    }
    
}
